package net.zjitc.dao.impl;

import net.zjitc.dao.UserDao;
import net.zjitc.domain.User;
import net.zjitc.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

/**
 * @Author admin
 * @Date 2019/3/4 10:40
 */
public class UserDaoImpl implements UserDao {
    @Override
    public User findByUsernameAndPassword(String username, String password)  {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from user where username=? and password=?";
        User user = null;
        try {
            user = runner.query(sql,new BeanHandler<User>(User.class),username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public User findByUsername(String username) {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from user where username = ?";
        User user = null;
        try {
            user = runner.query(sql,new BeanHandler<User>(User.class),username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public void add(User user) {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "INSERT INTO USER(username,password) VALUES (?,?)";
        try {
           runner.update(sql, new Object[]{user.getUsername(), user.getPassword()});
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public User findById(String uid) {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from user where uid=?";
        User user = null;
        try {
            user = runner.query(sql,new BeanHandler<User>(User.class),uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public void update(User user, String uid) throws SQLException {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "update user set username = ?,phone = ?,email=? where uid=?";
        runner.update(sql,new Object[]{user.getUsername(),user.getPhone(),user.getEmail(),uid});

    }
}
